package com.bsoft.project.service;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.project.http.HttpUrlConnectionToInterface;
import com.bsoft.project.mapper.DzfpUploadMapper;
import com.bsoft.project.model.KpxxVo;
import com.bsoft.project.utils.Base64Util;
import com.bsoft.project.utils.DzfpHttpJsonCreate;
import com.bsoft.project.utils.StringUtils;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 褚国强
 * @Date: 2020/07/08/22:26
 * @Description:
 */
@Service
public class DzfpUploadService {

	 private final Logger logger = LoggerFactory.getLogger(DzfpUploadService.class);
	
    @Autowired
    private DzfpUploadMapper dzfpUploadMappersss;


	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月23日 下午3:45:34
	* @Description: TODO
	* @version 1.0
	* @parameter
	* @since
	* @return
	*/
	public List<HashMap<String,Object>> getDzfpUploadList() {
		// TODO Auto-generated method stub
		return dzfpUploadMappersss.getDzfpUploadList();
	}


	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月26日 上午9:05:09
	* @Description: 发送财政单位端票据开具日报
	* @version 1.0
	* @parameter
	* @since
	* @return
	*/
	@Transactional
	public HashMap<String,Object> dzfpDailyReport() throws Exception {
		// TODO Auto-generated method stub
		int rbCount  = dzfpUploadMappersss.getRbxxCount();
		if(rbCount>0){
//			dzfpUploadMappersss.updateGhjs();  // 挂号结算
//			dzfpUploadMappersss.updateMzjs();  // 门诊结算
//			dzfpUploadMappersss.updateZyjs();  // 住院结算
//			dzfpUploadMappersss.updateMzToBlue();  // 未作废的ms_mzxx改成蓝票
//			dzfpUploadMappersss.updateMzToRed();  // 已作废的ms_mzxx改成红票
		}
		HashMap<String,Object> params = new HashMap<String,Object>();
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String preDate = df.format(date);
		params.put("startTime", preDate + " 00:00:00");
		params.put("endTime", preDate + " 23:59:59");
		params.put("pjlx", 1);
		List<HashMap<String,Object>> blueList = dzfpUploadMappersss.getJsfpTotalCount(params);   // 获取红发票各种数量  发票总额
		params.put("pjlx", 2);
		List<HashMap<String,Object>> redList = dzfpUploadMappersss.getJsfpTotalCount(params);   // 获取蓝发票各种数量  发票总额
		logger.info("------------------------------" + params);
		
		if((blueList.size() + redList.size())==0) return null;
		
		HashMap<String,Object> rbxxMap = new HashMap<String,Object>();		
		
		rbxxMap.put("enterGuid", getTxcsInfo("DZFP_DWBM"));  // 字典查询  电子发票所属单位编码	
		
		rbxxMap.put("reportDate", preDate.replace("-", ""));
		if(blueList.size()>0){
			rbxxMap.put("NoramlCount", blueList.get(0).get("KPSL"));
			rbxxMap.put("NoramlMoney", blueList.get(0).get("KPJE"));
		}else{
			rbxxMap.put("NoramlCount", "0");
			rbxxMap.put("NoramlMoney", "0.00");
		}
		if(redList.size()>0){
			rbxxMap.put("RedCount", redList.get(0).get("KPSL"));
			rbxxMap.put("RedMoney", redList.get(0).get("KPJE"));
		}else{
			rbxxMap.put("RedCount", "0");
			rbxxMap.put("RedMoney", "0.00");
		}
		
		logger.info("----------发送财政单位端票据开具日报 setDailyReport 数据包-----------" + JSON.toJSONString(rbxxMap));		

		JSONObject reqStr = setPostRequest("setDailyReport",rbxxMap);
		
		rbxxMap.put("reportDate", preDate);
		return parseResult(rbxxMap,reqStr);
	}
	
	
	
	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月26日 上午9:05:09
	* @Description: 发送医院his端实际缴款日报
	* @version 1.0
	* @parameter
	* @since
	* @return
	*/
	@Transactional
	public HashMap<String,Object> dzfpHisDailyReport() throws Exception {
		// TODO Auto-generated method stub
//		int rbCount  = dzfpUploadMappersss.getRbxxCount();
//		if(rbCount>0){
//			
//		}
		HashMap<String,Object> params = new HashMap<String,Object>();
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String preDate = df.format(date);
		params.put("startTime", preDate + " 00:00:00");
		params.put("endTime", preDate + " 23:59:59");
		params.put("pjlx", 1);
		List<HashMap<String,Object>> jfList = dzfpUploadMappersss.getHisJsfpTotalCount(params);   // 获取缴费总额
		params.put("pjlx", 2);
		List<HashMap<String,Object>> tfList = dzfpUploadMappersss.getHisJsfpTotalZfCount(params);   // 获取退费总额
		logger.info("------------------------------" + params);
		
		
		HashMap<String,Object> rbxxMap = new HashMap<String,Object>();		
			
		rbxxMap.put("enterGuid", getTxcsInfo("DZFP_DWBM"));  // 字典查询  电子发票所属单位编码		
		
		rbxxMap.put("reportDate", preDate.replace("-", ""));
		if(jfList.size()>0){
			rbxxMap.put("HNoramlCount", jfList.get(0).get("SFSL"));
			rbxxMap.put("HNoramlMoney", jfList.get(0).get("SFSUM"));
		}else{
			rbxxMap.put("HNoramlCount", "0");
			rbxxMap.put("HNoramlMoney", "0.00");
		}
		if(tfList.size()>0){
			rbxxMap.put("HRedCount", tfList.get(0).get("SFSL"));
			rbxxMap.put("HRedMoney", tfList.get(0).get("SFSUM"));
		}else{
			rbxxMap.put("HRedCount", "0");
			rbxxMap.put("HRedMoney", "0.00");
		}
		
		logger.info("----------发送医院his端实际缴款日报 setHisDailyReport  数据包-----------" + JSON.toJSONString(rbxxMap));		

		JSONObject reqStr = setPostRequest("setHisDailyReport", rbxxMap);
		
		rbxxMap.put("reportDate", preDate);
		return parseResult(rbxxMap,reqStr);
	}
	
	
	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月26日 上午9:05:09
	* @Description: 发起电子票据签名请求（单位无签名服务器）
	* @version 1.0
	* @parameter
	* @since
	* @return
	*/
	@Transactional
	public HashMap<String,Object> setEInvoiceInfoForEnter() throws Exception {
		HashMap<String,Object> params = new HashMap<String,Object>();
		Calendar calendar = Calendar.getInstance();
		
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String preDate = df.format(date);
		params.put("beginTime", preDate); 
		
		calendar.add(Calendar.DATE, 2); //明天日期
		date = calendar.getTime();
		preDate = df.format(date);
		params.put("endTime", preDate); 
		
		
		List<HashMap<String,Object>> jsfpList = dzfpUploadMappersss.getScxxList(params); 
		
		for(HashMap<String,Object> jsfpInfo: jsfpList){	
			HashMap<String,Object> dzfpMap = new HashMap<String,Object>();	
			dzfpMap.put("enterGuid", getTxcsInfo("DZFP_DWBM"));  // 字典查询  电子发票所属单位编码		
			
			String signContent = getSignContent(jsfpInfo);
			
			dzfpMap.put("SerialNumber", jsfpInfo.get("SerialNumber"));
			dzfpMap.put("SignContent", signContent);
			logger.info("---------------------" + JSON.toJSONString(dzfpMap));		

			JSONObject reqStr = setPostRequest("setEInvoiceInfoForEnter", dzfpMap);
			
			dzfpMap.put("reportDate", preDate);		
			
			parseResult(dzfpMap,reqStr);
		}
		
		
		return null;
	}
	
	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月26日 上午9:05:09
	* @Description: 发起电子票据签名请求（单位有签名服务器）
	* @version 1.0
	* @parameter
	* @since
	* @return
	*/
	@Transactional
	public HashMap<String,Object> setEInvoiceInfo() throws Exception {

		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String preDate = df.format(date);
		
		HashMap<String,Object> dzfpMap = new HashMap<String,Object>();	
		dzfpMap.put("enterGuid", getTxcsInfo("DZFP_DWBM"));  // 字典查询  电子发票所属单位编码		
		dzfpMap.put("beginTime", preDate); 
		calendar.add(Calendar.DATE, 2); //明天日期
		date = calendar.getTime();
		preDate = df.format(date);
		dzfpMap.put("endTime", preDate); 
		
		logger.info("---------------------" + JSON.toJSONString(dzfpMap));		

		JSONObject reqStr = setPostRequest("setEInvoiceInfo", dzfpMap);
		
		dzfpMap.put("reportDate", preDate);
		return parseResult(dzfpMap,reqStr);
	}
	
	
	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月26日
	* @Description: 发送接口请求，包含数据包组包
	* @version 1.0
	* @parameter
	* @since
	* @return String
	*/
	private String getSignContent(HashMap<String,Object> params){
		
		KpxxVo kpxx = new KpxxVo();
		kpxx.setPjly(params.get("PJLY").toString());
		kpxx.setFphm(params.get("FPHM").toString());
		kpxx.setPjdm(params.get("PJHM").toString());
		
		if("3".equals(params.get("PJLY").toString())){   // 具体看sql。。。因为union的问题
			kpxx.setBrid(params.get("BRID").toString());
		}else{
			kpxx.setJzxh(params.get("BRID").toString());
		}
		//
		//分配发票号码
		
		if(StringUtils.isEmpty(params.get("PJHM"))){
			presetPjhm(kpxx);
		}
		return null;
	}
	
	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月26日
	* @Description: 统一预分配票据代码
	* @version 1.0
	* @parameter
	* @since
	* @return 
	*/
	private void presetPjhm(KpxxVo kpxx){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		DateFormat df = new SimpleDateFormat("yyyy");
		String preDate = df.format(date).substring(2);
		if("3".equals(kpxx.getPjly())){  //住院
			String pjdm = getTxcsInfo("DZFP_PJDM_ZY");
			if(!preDate.equals(pjdm.substring(pjdm.length()-2,pjdm.length()))){  //跨年度修改票据代码
				
			}
		}else{  //门诊
			String pjdm = getTxcsInfo("DZFP_PJDM_MZ");
		}
	}
	
	/**
	* @author : 褚国强
	* @date 创建时间：2021年7月26日
	* @Description: 发送接口请求，包含数据包组包
	* @version 1.0
	* @parameter
	* @since
	* @return JSONObject
	*/
	private JSONObject setPostRequest(String method,HashMap<String,Object> params) throws Exception{
		HashMap<String,Object> postMap = new HashMap<String,Object>();  
		postMap.put("method", method);
		
		/* *
		 * 正式路径 参数
		 * */
//		String url = getTxcsInfo("DZFP_URL");
//		postMap.put("app_id", getTxcsInfo("DZFP_APPID"));
//		postMap.put("app_key", getTxcsInfo("DZFP_KEY"));
		
		
		/* *
		 * 测试路径 参数
		 * */
		String url = "http://10.173.113.126:8058/eBillHisServer/medical/eInvoice";
		postMap.put("app_id", "9a82274aaac9465f9ff26d18b8e6ba94");
		postMap.put("app_key", "346792398c61458babac0f78a922b771");
		
		postMap.put("format", getTxcsInfo("DZFP_FORMAT"));
		postMap.put("version", getTxcsInfo("DZFP_VERSION"));
		postMap.put("message", Base64Util.encode(JSON.toJSONString(params)));
		HashMap<String, String> dzfpMap = DzfpHttpJsonCreate.getDzfpHttpJson(postMap);		
		
		logger.info("----------加密前接口发送参数包-----------" + JSON.toJSONString(postMap));
		logger.info("----------加密后接口发送参数包-----------" + JSON.toJSONString(dzfpMap));
		
//		String reqStr = HttpUrlConnectionToInterface.sendPost(url, null, dzfpMap);  // 发送 post 请求
		
		String reqStr = HttpUrlConnectionToInterface.sendPost(url, dzfpMap);
		
		JSONObject result = JSON.parseObject(reqStr);
		
		logger.info("----------返回包-----------" + result.toString());
		
		return result;
	}
	
	
	private HashMap<String,Object> parseResult(HashMap<String,Object> params,JSONObject result){
		HashMap<String,Object> returnMap = new HashMap<String,Object>();
		String code = result.getString("is_success");  // 无用。。判断msg 即可
		returnMap.put("code", code);
		String succMsg =  Base64Util.decode(result.getString("message"));
		String errorMsg =  Base64Util.decode(result.getString("error_message"));
		
		if(StringUtils.isNotEmpty(succMsg)){
			params.put("scbz", 1);
			params.put("msg", succMsg);
			returnMap.put("msg", succMsg);
			dzfpUploadMappersss.inserRzxx(params);
			return returnMap;
		}else{
			params.put("scbz", 0);
			params.put("msg", errorMsg);
			returnMap.put("msg", errorMsg);
			dzfpUploadMappersss.inserRzxx(params);
			return returnMap;
		}
	}
	
	public String getTxcsInfo(String csmc){
		HashMap<String,Object> dictMap = dzfpUploadMappersss.getTxcsInfo(csmc);
		return dictMap.get("CSZ").toString();
	}
	
	
	public HashMap<String, Object> rsfComIfsService(HashMap<String,Object> param) throws Exception {
		HashMap<String, Object> returnMap = new HashMap<String, Object>();

//		List<String[]> list = new ArrayList<>();
		logger.info("---------------------------- read file ");
//		LineIterator lineIterator = FileUtils.lineIterator(new File("D:\\Backup\\桌面\\chugiegie\\tab.txt"), "utf-8");
//		// LineIterator lineIterator = FileUtils.lineIterator(new File("C:\\Users\\小手我破的处\\Desktop\\康慈 精神病图谱生成\\tab.txt"), "utf-8");
//		int i = 1;
//		while (lineIterator.hasNext()) {
//			String result = lineIterator.next();
//			list.add(result.split("\t"));
//		}
		long beginTime = System.currentTimeMillis();
//		FileInputStream fileInputStream = new FileInputStream("C:\\Users\\小手我破的处\\Desktop\\康慈 精神病图谱生成\\tab.txt"); // 179055
		FileInputStream fileInputStream = new FileInputStream("D:\\Backup\\桌面\\chugiegie\\tab.txt");
		Scanner scanner = new Scanner(fileInputStream, "utf-8");
		int i = 1;
		while (scanner.hasNext()) {
			String result = scanner.nextLine();
			String[] arr = result.split("\t");
			if(arr.length == 97){  // 有些行 数据不对
				dzfpUploadMappersss.insertYbmlStr(arr[0]);
				if(i == 5000){
					logger.info("---------------------------- 5000");
				}
				if(i == 10000){
					logger.info("---------------------------- 10000");
				}
				
				if(i == 15000){
					logger.info("---------------------------- 15000");
					break;
				}
				i++;
//				list.add(arr);				
			}
//			if(list.size() == 5000){ // 5000 条插入一次数据库。。。用来释放内存
//				break;
//				logger.info("---------------------------- list size " + list.size());
//				dzfpUploadMappersss.insertYbml(list);
//				list.clear(); // 释放内存
//			}
		}
		fileInputStream.close();
		scanner.close();
//		logger.info("---------------------------- list size " + list.size());
//		if(list.size() > 0){ 
//			dzfpUploadMappersss.insertYbml(list); // 将不满5000的剩余数据插入
//		}
		long endTime = System.currentTimeMillis();
		logger.info("---------------------------- 总时间（毫秒）：" + (endTime - beginTime));
		return returnMap;
	}
}
